package com.tbit.uqbike.webmanager.controller;

import com.github.pagehelper.PageInfo;
import com.tbit.common.entity.pojo.dto.BarChartRepairDTO;
import com.tbit.common.entity.pojo.vo.DateResult;
import com.tbit.uqbike.object.pojo.statistics.ExportPowerLog;
import com.tbit.uqbike.object.pojo.statistics.RepairLog;
import com.tbit.uqbike.object.view.JsonResult;
import com.tbit.uqbike.service.business.RepairLogService;
import com.tbit.uqbike.webmanager.util.Assert;
import com.tbit.uqbike.webmanager.util.PowerLogExportUtil;
import com.tbit.uqbike.webmanager.util.ServletUtils;
import com.tbit.uqbike.webmanager.util.StringUtil;
import com.tbit.uqbike.webmanager.util.excel.ExportExcelUtil;
import com.tbit.uqbike.webmanager.util.excel.ExportExcelWrapper;
import com.tbit.utils.Excel;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.RequestContext;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: chen
 * @Description: 维修统计
 * @Date: 创建于 16:45 2020/3/13
 */
@Slf4j
@Validated
@RestController
@RequestMapping(value = "/repairLogStat", produces = BaseController.MEDIA_JSON_UTF8)
public class RepairLogController extends BaseController {
    @Autowired
    private RepairLogService repairLogService;

    /**
     * 柱状图数据
     * @param barChartRepairDTO 请求参数
     * @return JsonResult
     */
    @RequestMapping("/statisticsByTime")
    public JsonResult statisticsByTime(BarChartRepairDTO barChartRepairDTO) {
        List<List<DateResult>> list = repairLogService.statisticsByTime(barChartRepairDTO);
        return JsonResult.ok(list);
    }

    /**
     * 分页查询详细
     */
    @RequestMapping("/queryPage")
    public JsonResult queryPage(@NotNull(message = "ver.accountId.notNull") Integer accountId, String machineNO, String userCode,
                                Integer accountUserId, Long startTime, Long endTime, @RequestParam(required = false, value = "regionIds") String regionIds, @RequestParam(defaultValue = "1") Integer pageNO, @RequestParam(defaultValue = "10") Integer rowCount) {
        List<Integer> regionIdList = StringUtil.getIntegerList(regionIds);
        List<RepairLog> list = repairLogService.queryPage(accountId, machineNO, userCode, accountUserId, startTime, endTime, regionIdList, pageNO, rowCount);
        Integer total = repairLogService.queryCount(accountId, machineNO, userCode, accountUserId, startTime, endTime, regionIdList);
        return JsonResult.ok(list, total);
    }

    /**
     * 导出
     */
    @RequestMapping("/exportByTime")
    public void exportByTime(Integer accountId, Integer accountUserId, Long startTime, Long endTime,
                             @RequestParam(required = false, value = "regionIds") String regionIds,
                             HttpServletResponse response) {
        Assert.notNull(accountId, "ver.accountId.notNull");
        Assert.notNull(startTime, "ver.startTime.notNull");
        Assert.notNull(endTime, "ver.endTime.notNull");
//        if (null == accountUserId) {
//            throw new BaseException(SystemCodeEnum.SELECT_OPERATION_AND_MAINTENANCE_PERSONNEL);
//        }
        RequestContext context = getLogin(ServletUtils.getRequest()).getContext();
        List<RepairLog> list = repairLogService.exportByTime(accountId, accountUserId, startTime, endTime, regionIds);
        List<String[]> exportList = PowerLogExportUtil.getExportContent(null, null, null, list, context);
        ExportExcelWrapper<String[]> export = new ExportExcelWrapper<>();
        export.exportExcel(context.getMessage("excel_head_repair"), context.getMessage("excel_head_repair"), null, exportList, response, ExportExcelUtil.EXCEL_FILE_2003);
//        ExportExcelUtils.exportExcel(response, "维修统计", exportList);
    }

    /**
     * 维修总详情
     */
    @RequestMapping("/getByType")
    public JsonResult getByType(@NotNull(message = "ver.accountId.notNull") Integer accountId, Integer accountUserId,
                                @NotNull(message = "ver.startTime.notNull") Long startTime,
                                @RequestParam(required = false, value = "regionIds") String regionIds,
                                @RequestParam(required = false, value = "type") Integer type,
                                @NotNull(message = "ver.endTime.notNull") Long endTime,
                                @RequestParam(defaultValue = "10") Integer rowCount,
                                @RequestParam(defaultValue = "1") Integer pageNO,
                                @RequestParam(required = false, value = "sort") String sort, HttpServletResponse response) {
        List<Integer> regionIdList = StringUtil.getIntegerList(regionIds);
        List<ExportPowerLog> list = repairLogService.getByType(accountId, accountUserId, startTime, endTime, rowCount, pageNO, regionIdList, type);
        /**升序排列*/
        List<ExportPowerLog> ascendingList = list.stream().sorted(Comparator.comparing(ExportPowerLog::getTotal)).collect(Collectors.toList());
        /**降序排列*/
        List<ExportPowerLog> descendingList = list.stream().sorted(Comparator.comparing(ExportPowerLog::getTotal).reversed()).collect(Collectors.toList());
        PageInfo pageInfo = new PageInfo();
        if ("asc".equals(sort)) {
            pageInfo = new PageInfo(ascendingList);
        } else if ("desc".equals(sort)) {
            pageInfo = new PageInfo(descendingList);
        }
        return JsonResult.ok(pageInfo.getList(), (int) pageInfo.getTotal());
    }


    @RequestMapping("/exportByTimeAndByRegionId")
    public void exportByTimeAndByRegionId(@NotNull(message = "ver.accountId.notNull") Integer accountId, Integer accountUserId, @NotNull(message = "ver.startTime.notNull") Long startTime, @RequestParam(required = false, value = "regionIds") String regionIds, @RequestParam(required = false, value = "type") Integer type,
                                          @NotNull(message = "ver.endTime.notNull") Long endTime, @RequestParam(defaultValue = "10") Integer rowCount, @RequestParam(defaultValue = "1") Integer pageNO, HttpServletResponse response) {
        try {
            List<Integer> regionIdList = StringUtil.getIntegerList(regionIds);
            List<ExportPowerLog> list = repairLogService.getByType(accountId, accountUserId, startTime, endTime, rowCount, pageNO, regionIdList, type);
            List<String> cellNameList = new ArrayList<>();
            int row = 1;
            String fileName = "维修记录.xls";
            String title = "维修记录";
            HSSFWorkbook excel = null;
            if (type == 0) {
                cellNameList.add("手机号码");
                cellNameList.add("姓名");
                cellNameList.add("总次数");
                excel = Excel.createExcel(title, cellNameList);
                for (ExportPowerLog exportPowerLog : list) {
                    List<String> excelData = new ArrayList<>();
                    excelData.add(exportPowerLog.getPhone() + "");
                    excelData.add(exportPowerLog.getName() + "");
                    excelData.add(exportPowerLog.getTotal().toString());
                    excel = Excel.createExcelData(excel, excelData, row);
                    row++;
                }
            } else if (type == 1) {
                cellNameList.add("分区名");
                cellNameList.add("总次数");
                excel = Excel.createExcel(title, cellNameList);
                for (ExportPowerLog exportPowerLog : list) {
                    List<String> excelData = new ArrayList<>();
                    excelData.add(exportPowerLog.getRegionName().toString());
                    excelData.add(exportPowerLog.getTotal().toString());
                    excel = Excel.createExcelData(excel, excelData, row);
                    row++;
                }
            }
            OutputStream out = null;
            String headStr = "attachment; filename=\"" + new String(fileName.getBytes("utf-8"), "ISO8859-1") + "\"";
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", headStr);
            out = response.getOutputStream();
            excel.write(out);
            out.flush();
            out.close();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

    }
}
